package org.porridge.util.qiniu;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.porridge.util.Constant;

import com.qiniu.api.auth.AuthException;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.config.Config;
import com.qiniu.api.fop.ImageInfo;
import com.qiniu.api.fop.ImageInfoRet;
import com.qiniu.api.io.IoApi;
import com.qiniu.api.io.PutExtra;
import com.qiniu.api.io.PutRet;
import com.qiniu.api.rs.Entry;
import com.qiniu.api.rs.PutPolicy;
import com.qiniu.api.rs.RSClient;
import com.qiniu.api.rsf.ListItem;
import com.qiniu.api.rsf.ListPrefixRet;
import com.qiniu.api.rsf.RSFClient;
import com.qiniu.api.rsf.RSFEofException;

/**
 * 七牛存储工具类
* @Title: QiniuUtil.java 
* @Package org.porridge.util.qiniu 
* @Description: TODO 
* @author porridge
* @url  http://www.prdblog.com/
* @email  mfkwfc@gmail.com   
* @date 2014年4月21日 下午10:06:45 
* @version V1.0
 */
public class QiniuUtil {
	private QiniuUtil(){}
	private static Mac mac=initQiniu();
	
	/**
	 * 查询当前加密码
	 * 需要传入空间名称
	 * @return
	 */
	public static String getUptoken(String qiniuname){
		String uptoken="";
		PutPolicy putPolicy = new PutPolicy(qiniuname);
		 try {
			uptoken = putPolicy.token(mac);
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (AuthException e) {
			e.printStackTrace();
		}
		return uptoken;
	}
	
	private static Mac initQiniu(){
		Config.ACCESS_KEY=Constant.SETTING.getQiniu_account();
		Config.SECRET_KEY=Constant.SETTING.getQiniu_password();
		mac = new Mac(Config.ACCESS_KEY, Config.SECRET_KEY);
        return mac;
	}
	/**
	 * 上传文件
	 * @param name
	 * @param url
	 * @return
	 */
	public static boolean uploadFile(String qiniuname,String name,String url){
		boolean bl=false;
		if(url!=null && url.trim().length()>0){
			File file=new File(url);
			if(file.isFile()){
				PutExtra extra = new PutExtra();
		        String key = name;
		        PutRet ret = IoApi.putFile(getUptoken(qiniuname),key,url,extra);
		        bl=ret.ok();
			}
		}
		return bl;
	}
	/**
	 * 查询图片
	 * @param prifix  查询前缀
	 * @return
	 */
	public static List<ListItem> getList(String qiniuname,String prifix,int number){
	        Mac mac =initQiniu();
	        RSFClient client = new RSFClient(mac);
	        String marker = "";
	        List<ListItem> all = new ArrayList<ListItem>();
	        ListPrefixRet ret = null;
	        while (true) {
	            ret = client.listPrifix(qiniuname,Constant.SETTING.getQunui_first()+(prifix!=null?"/"+prifix+"/":""), marker,number);
	            marker = ret.marker;
	            all.addAll(ret.results);
	            if (!ret.ok()) {
	                break;
	            }
	        }
	        if (ret.exception.getClass() != RSFEofException.class){
	            System.out.println("七牛列表查询出现错误...");
	        }
	        return all;
	}
}
